package com.ext.aic.handler;

import android.app.Activity;
import android.content.Context;

import com.ext.aic.AICApplication;
import com.ext.aic.R;
import com.ext.aic.apis.other.AppUpdateRequest;
import com.ext.aic.beans.response.AppUpdateBody;
import com.ext.aic.components.AppUpdatePopup;
import com.ext.aic.events.OnAppUpdateListener;
import com.ext.aic.utils.AppUtils;
import com.ext.aic.utils.XPopupUtils;
import com.eyinfo.mpkv.MPLocalKV;
import com.king.app.updater.AppUpdater;
import com.king.app.updater.UpdateConfig;
import com.king.app.updater.callback.AppUpdateCallback;
import com.king.app.updater.http.OkHttpManager;

//应用更新
public class AppUpdateHandler implements OnAppUpdateListener {

    private Context context;
    private long checkInterval = 300000;
    private String checkTimeKey = "18643afb0b748439";
    private AppUpdateBody updateBody;
    private boolean updating;

    public void checkUpdate(Context context, boolean nowCheck) {
        this.context = context;
        if (!nowCheck) {
            long preTime = MPLocalKV.getInstance().getLong(checkTimeKey, 0);
            long diffTime = System.currentTimeMillis() - preTime;
            if (diffTime <= checkInterval) {
                return;
            }
            long pauseCheckUpdateTime = MPLocalKV.getInstance().getLong("pauseCheckUpdateTime", 0);
            long diff = System.currentTimeMillis() - pauseCheckUpdateTime;
            if (pauseCheckUpdateTime > 0 && diff <= 30 * 60000) {
                return;
            }
            if (updating) {
                return;
            }
        }
        updating = true;
        appUpdateRequest.request();
    }


    private AppUpdateRequest appUpdateRequest = new AppUpdateRequest() {
        @Override
        protected void onAppUpdateSuccess(AppUpdateBody response) {
            updateBody = response;
            long currentVersionCode = AppUtils.getInstance().getVersionCode();
            long buildNumber = response.getBuildNumber();
            long minBuildNumber = response.getMinBuildNumber();
            if (currentVersionCode <= minBuildNumber) {
                showUpdateDialog();
                return;
            }
            if (buildNumber > currentVersionCode) {
                showUpdateDialog();
            }
        }

        @Override
        protected void onAppUpdateEnd() {
            updating = false;
        }
    };

    private void showUpdateDialog() {
        Activity currentActivity = AICApplication.getInstance().getCurrentActivity();
        AppUpdatePopup appUpdatePopup = new AppUpdatePopup(currentActivity);
        appUpdatePopup.setOnAppUpdateListener(this);
        XPopupUtils.getInstance().showCustomDialog(currentActivity, appUpdatePopup);
    }

    //https://jenly1314.github.io/AppUpdater/api/app-updater/com.king.app.updater/-update-config/index.html
    private UpdateConfig getUpdateConfig() {
        UpdateConfig updateConfig = new UpdateConfig();
        updateConfig.setApkMD5("4cc1d5e26dcab81a07a795218b89fe2e");
        updateConfig.setDeleteCancelFile(true);
        updateConfig.setInstallApk(true);
        updateConfig.setReDownload(true);
        updateConfig.setReDownloads(2);
        updateConfig.setShowNotification(true);
        updateConfig.setShowPercentage(true);
        updateConfig.setSound(false);
        updateConfig.setSupportCancelDownload(false);
        updateConfig.setVibrate(false);
        updateConfig.setVersionCode(AppUtils.getInstance().getVersionCode());
        updateConfig.setChannelId("aic_app_update");
        updateConfig.setChannelName(context.getString(R.string.update_title));
        String packageName = AICApplication.getInstance().getPackageName();
        String versionName = AppUtils.getInstance().getVersionName();
        updateConfig.setFilename(String.format("%s_%s.apk", packageName, versionName));
        updateConfig.setNotificationIcon(R.mipmap.ic_launcher);
        updateConfig.setNotificationId(1000);
        updateConfig.setUrl(updateBody.getDownloadUrl());
        return updateConfig;
    }

    @Override
    public boolean isForceUpdate() {
        long currentVersionCode = AppUtils.getInstance().getVersionCode();
        long minBuildNumber = updateBody.getMinBuildNumber();
        return currentVersionCode <= minBuildNumber;
    }

    @Override
    public void onAppUpdate(AppUpdateCallback callback) {
        UpdateConfig updateConfig = getUpdateConfig();
        AppUpdater appUpdater = new AppUpdater(context, updateConfig);
        appUpdater.setHttpManager(OkHttpManager.getInstance());
        appUpdater.setUpdateCallback(callback)
                .start();
    }

    @Override
    public AppUpdateBody getAppUpdateBody() {
        return updateBody;
    }
}
